﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace CacheEngine
{
    /// <summary>缓存管理工厂</summary>
    public class CacheManagerFactory : ICacheManagerFactory
    {
        private static CacheManagerFactory _current = new CacheManagerFactory();
        public static CacheManagerFactory Current
        {
            get
            {
                return _current;
            }
            set
            {
                _current = value;
            }
        }

        protected CacheManagerFactory()
        { }

        //todo: cache these reults
        /* I think that the CacheEngine and the KeyGenerator should be singletons for each
         * type.  That way we can cache them easily by type.  Not quite sure what to do with the 
         * DefaultCacheManager.
         */
        public virtual bool TryGetCacheManager(MethodInfo methodInfo, out ICacheManager cacheManager)
        {
            cacheManager = null;
            bool found = false;
            object[] attributes = methodInfo.GetCustomAttributes(typeof(CacheEngineAttribute), false);
            if (attributes != null && attributes.Length > 0)
            {
                var cacheMoneyAttribute = (CacheEngineAttribute)attributes[0];
                ICacheEngine cacheEngine = (ICacheEngine)Activator.CreateInstance(cacheMoneyAttribute.CacheEngineType);
                IKeyGenerator keyGenerator = (IKeyGenerator)Activator.CreateInstance(cacheMoneyAttribute.KeyGeneratorType);

                cacheManager = new DefaultCacheManager { CacheEngine = cacheEngine, KeyGenerator = keyGenerator, Attribute = cacheMoneyAttribute };

                found = true;
            }

            return found;
        }
    }
}
